package com.world.cat.controller.generate;

import com.world.cat.service.generate.FieldService;
import com.world.common.generate.auto.Action;
import com.world.common.generate.auto.QFieldInfo;
import com.world.common.generate.auto.QMapping;
import com.world.common.pojo.Result;
import com.world.common.pojo.WorldPage;
import com.world.common.util.DateUtil;
import com.world.common.util.Excel;
import com.world.common.util.SysUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.*;

//自动代码生成
@Controller
@RequestMapping(value = "/auto")
public class AutoController {
    @Resource
    private FieldService fieldService;

    @QMapping(relatedUrl = "/auto/home")
    @RequestMapping(value = "/home")
    public String home(Model model, String o, WorldPage worldPage, String params) throws Exception {
        Class clazz = fieldService.obtainClass(o);
        Page page = fieldService.queryPageByHql(clazz, params, worldPage.getPageRequest());
        model.addAttribute("page", page);
        Map<String, List<QFieldInfo>> qFieldMap = FieldService.getFieldMap(clazz);
        model.addAttribute("fieldMap", qFieldMap);
        model.addAttribute("qClassActions", FieldService.getClassActionInfo(clazz));
        model.addAttribute("o", o);
        return "generate/auto-ace";
    }

    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String params, String o, WorldPage worldPage) throws Exception {
        worldPage.setProperties("createTime");
        Class clazz = fieldService.obtainClass(o);
        Page page = fieldService.queryPageByHql(clazz, params, worldPage.getPageRequest());
        return page;
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public Object save(String o, String params) throws Exception {
        Class clazz = fieldService.obtainClass(o);
        Result result = fieldService.saveByHql(clazz, params);
        return result;
    }

    @RequestMapping(value = "/del")
    @ResponseBody
    public Object del(String o, String[] ids) {
        Class clazz = fieldService.obtainClass(o);
        fieldService.del(clazz, ids);
        return new Result(true);
    }

    @RequestMapping(value = "/edit")
    public String edit(Model model, String o, String id) throws Exception {
        Class clazz = fieldService.obtainClass(o);
        Object object = fieldService.getEntity(clazz, id);
        Map<String, List<QFieldInfo>> qFieldMap = FieldService.getFieldMap(clazz);
        model.addAttribute("fieldMap", qFieldMap);
        model.addAttribute("obj", object);
        return "generate/auto-edit";
    }

    @RequestMapping(value = "/view")
    public String view(Model model, String o, String id) throws Exception {
        Class clazz = fieldService.obtainClass(o);
        Object object = fieldService.getEntity(clazz, id);
        Map<String, List<QFieldInfo>> qFieldMap = FieldService.getFieldMap(clazz);
        model.addAttribute("fieldMap", qFieldMap);
        model.addAttribute("obj", object);
        return "generate/auto-view";
    }

    @RequestMapping(value = "/add")
    public String add(Model model, String o) throws Exception {
        Class clazz = fieldService.obtainClass(o);
        Map<String, List<QFieldInfo>> qFieldMap = FieldService.getFieldMap(clazz);
        model.addAttribute("fieldMap", qFieldMap);
        return "generate/auto-add";
    }

    @RequestMapping("/export")
    public void exportExcel(HttpServletResponse response, String params, String o, String fileName) throws Exception {
        if (SysUtil.isEmpty(o)) {
            return;
        }
        OutputStream os = null;
        List<String[]> excel = new ArrayList<>();
        List<String> excelHeadList = new ArrayList<>();
        List<String> fieldList = new ArrayList<>();
        Class clazz = fieldService.obtainClass(o);
        Map<String, List<QFieldInfo>> qFieldMap = fieldService.getFieldMap(clazz);
        List<QFieldInfo> qFieldInfos = qFieldMap.get(Action.export.name());
        Map<String, Method> methodMap = new HashMap<>();
        for (QFieldInfo fieldInfo : qFieldInfos) {
            excelHeadList.add(fieldInfo.getNickname());
            fieldList.add(fieldInfo.getName());
            Method method = clazz.getDeclaredMethod("get" + StringUtils.capitalize(fieldInfo.getName()), null);
            methodMap.put(fieldInfo.getName(), method);
        }
        String[] head = new String[excelHeadList.size()];
        excelHeadList.toArray(head);
        excel.add(head);
        List exchangedList = fieldService.queryByHql(clazz, params);
        for (int i = 0; i < exchangedList.size(); i++) {
            String[] content = new String[head.length];
            Object obj = exchangedList.get(i);
            for (int j = 0; j < fieldList.size(); j++) {
                String field = fieldList.get(j);
                Method method = methodMap.get(field);
                content[j] = String.valueOf(method.invoke(obj, null));
            }
            excel.add(content);
        }
        String dateStr = DateUtil.format("yyyyMMddHHmmss", new Date());
        String filename = fileName + dateStr + ".xls";//设置下载时客户端Excel的名称
        filename = new String(filename.getBytes("utf-8"), "iso-8859-1");//处理中文文件名
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + filename);
        Workbook workbook = Excel.simpleExportExcel(excel);
        os = response.getOutputStream();
        workbook.write(os);
        os.flush();
        os.close();
    }
}
